/**
 * @file CanvasSizeSelector.tsx
 * @description 画布尺寸选择器组件，提供预设尺寸和自定义尺寸的选择功能
 * @module CanvasSizeSelector
 */

import React, { useState } from 'react';
import styles from '../createDesign/CreateDesign.module.css';

// 导入预设尺寸的缩略图
import img1 from './images/app1.png';
import img2 from './images/app2.png';
import img3 from './images/app3.png';
import img4 from './images/app4.png';
import img5 from './images/app5.png';
import img6 from './images/app6.png';
import img7 from './images/app7.png';
import img8 from './images/app8.png';
import { useNavigate } from 'react-router-dom';

/**
 * 预设画布尺寸类型定义
 * @interface PresetSize
 * @property {string} id - 唯一标识符
 * @property {string} name - 尺寸名称
 * @property {number} width - 宽度(px)
 * @property {number} height - 高度(px)
 * @property {string} description - 描述信息
 * @property {string} color - 边框颜色
 * @property {boolean} [fixedWidth] - 是否固定宽度(可选)
 * @property {string} [imageUrl] - 缩略图URL(可选)
 */
interface PresetSize {
  id: string;
  name: string;
  width: number;
  height: number;
  description: string;
  color: string;
  fixedWidth?: boolean;
  imageUrl?: string;
}

/**
 * 组件属性类型定义
 * @interface CanvasSizeSelectorProps
 * @property {function} onCreateCanvas - 创建画布的回调函数，接收宽度和高度参数
 */
interface CanvasSizeSelectorProps {
  onCreateCanvas: (width: number, height: number) => void;
}

/**
 * 画布尺寸选择器组件
 * @component
 * @description 提供预设画布尺寸选择和自定义尺寸输入功能
 * @param {CanvasSizeSelectorProps} props - 组件属性
 * @returns {JSX.Element} 画布尺寸选择器组件
 */
const CanvasSizeSelector: React.FC<CanvasSizeSelectorProps> = ({ onCreateCanvas }) => {
  // 预设画布尺寸数据配置
  const presetSizes: PresetSize[] = [
    {
      id: 'banner',
      name: '广告banner',
      imageUrl: img1,
      width: 900,
      height: 500,
      description: '橙色标题栏，卡通人物与风景背景',
      color: 'orange'
    },
    {
      id: 'official-account',
      name: '公众号首页',
      imageUrl: img2,
      width: 900,
      height: 383,
      description: '黄蓝配色，自行车与二维码元素',
      color: 'blue'
    },
    {
      id: 'mobile-poster',
      name: '手机海报',
      imageUrl: img3,
      width: 1242,
      height: 2208,
      description: '蓝白配色，"招聘"字样突出',
      color: 'lightblue'
    },
    {
      id: 'ecommerce-full',
      name: '电商全屏海报',
      imageUrl: img4,
      width: 1920,
      height: 900,
      description: '红黄渐变底色，促销氛围设计',
      color: 'red'
    },
    {
      id: 'ecommerce-main',
      name: '电商主图/直通车',
      imageUrl: img5,
      width: 800,
      height: 800,
      description: '紫色背景，VIP标识与商品展示',
      color: 'purple'
    },
    {
      id: 'invitation',
      name: '电子邀请函',
      imageUrl: img6,
      width: 1242,
      height: 2208,
      description: '白底黑字，商务人物剪影',
      color: 'white'
    },
    {
      id: 'daily-sign',
      name: '日签',
      imageUrl: img7,
      width: 720,
      height: 1280,
      description: '蓝白配色，帆船与远方风景插画',
      color: 'lightblue'
    },
    {
      id: 'long-poster',
      name: '长图海报/营销海报',
      imageUrl: img8,
      width: 800,
      height: 2000,
      description: '白底黑字，竖版图文布局',
      color: 'white',
      fixedWidth: true
    }
  ];

  // 路由导航hook
  const navigate = useNavigate();

  /**
   * 状态管理
   * @state {PresetSize} selectedPreset - 当前选中的预设尺寸
   * @state {number} customWidth - 自定义宽度值
   * @state {number} customHeight - 自定义高度值
   * @state {boolean} isWidthLocked - 宽度是否锁定
   */
  const [selectedPreset, setSelectedPreset] = useState<PresetSize>(presetSizes[0]);
  const [customWidth, setCustomWidth] = useState<number>(presetSizes[0].width);
  const [customHeight, setCustomHeight] = useState<number>(presetSizes[0].height);
  const [isWidthLocked, setIsWidthLocked] = useState<boolean>(false);

  /**
   * 处理预设尺寸选择
   * @function handlePresetSelect
   * @param {PresetSize} preset - 选中的预设尺寸对象
   * @description 更新选中的预设尺寸并设置相应的宽度和高度值
   */
  const handlePresetSelect = (preset: PresetSize) => {
    setSelectedPreset(preset);
    setCustomWidth(preset.width);
    setCustomHeight(preset.height);
    setIsWidthLocked(!!preset.fixedWidth);
  };

  /**
   * 处理宽度输入变化
   * @function handleWidthChange
   * @param {React.ChangeEvent<HTMLInputElement>} e - 输入框变化事件
   * @description 更新自定义宽度值
   */
  const handleWidthChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newWidth = parseInt(e.target.value) || 0;
    setCustomWidth(newWidth);
  };

  /**
   * 处理高度输入变化
   * @function handleHeightChange
   * @param {React.ChangeEvent<HTMLInputElement>} e - 输入框变化事件
   * @description 更新自定义高度值
   */
  const handleHeightChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newHeight = parseInt(e.target.value) || 0;
    setCustomHeight(newHeight);
  };

  /**
   * 切换宽度锁定状态
   * @function toggleWidthLock
   * @description 切换宽度是否可编辑的状态
   */
  const toggleWidthLock = () => {
    setIsWidthLocked(!isWidthLocked);
  };

  return (
    <div className={styles.canvas_size_selector}>
      {/* 标题区域 */}
      <div className={styles.selector_header}>
        <h2 className={styles.selector_title}>选择画布尺寸</h2>
        <button className={styles.close_btn}>×</button>
      </div>
      
      {/* 主要内容区域 */}
      <div className={styles.selector_container}>
        {/* 左侧 - 热门场景预设尺寸列表 */}
        <div className={styles.preset_sizes}>
          <h3 className={styles.section_title}>热门场景</h3>
          
          {/* 渲染上半部分预设尺寸（前4个） */}
          <div className={styles.preset_row}>
            {presetSizes.slice(0, 4).map((preset) => (
              <div 
                key={preset.id}
                className={`${styles.preset_item} ${selectedPreset?.id === preset.id ? styles.selected : ''}`}
                style={{ borderColor: preset.color }}
                onClick={() => handlePresetSelect(preset)}
              >
                {/* 预设尺寸缩略图 */}
                {preset.imageUrl && (
                  <div className={styles.preset_thumbnail}>
                    <img src={preset.imageUrl} alt={preset.name} />
                  </div>
                )}
                {/* 预设尺寸信息 */}
                <div className={styles.preset_info}>
                  <div className={styles.preset_name}>{preset.name}</div>
                  <div className={styles.preset_dimensions}>{preset.width} × {preset.height}px</div>
                </div>
              </div>
            ))}
          </div>
          
          {/* 渲染下半部分预设尺寸（后4个） */}
          <div className={styles.preset_row}>
            {presetSizes.slice(4, 8).map((preset) => (
              <div 
                key={preset.id}
                className={`${styles.preset_item} ${selectedPreset?.id === preset.id ? styles.selected : ''}`}
                style={{ borderColor: preset.color }}
                onClick={() => handlePresetSelect(preset)}
              >
                {/* 预设尺寸缩略图 */}
                {preset.imageUrl && (
                  <div className={styles.preset_thumbnail}>
                    <img src={preset.imageUrl} alt={preset.name} />
                  </div>
                )}
                {/* 预设尺寸信息 */}
                <div className={styles.preset_info}>
                  <div className={styles.preset_name}>{preset.name}</div>
                  <div className={styles.preset_dimensions}>{preset.width} × {preset.height}px</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 右侧 - 自定义尺寸设置区域 */}
        <div className={styles.custom_size}>
          <h3 className={styles.section_title}>其他尺寸</h3>
          
          {/* 预设下拉选择 */}
          <div className={styles.form_group}>
            <select 
              className={styles.preset_select}
              value={selectedPreset?.id || ''}
              onChange={(e) => {
                const selected = presetSizes.find(p => p.id === e.target.value);
                if (selected) handlePresetSelect(selected);
              }}
            >
              {presetSizes.map((preset) => (
                <option key={preset.id} value={preset.id}>
                  {preset.name} {preset.width} × {preset.height}px
                </option>
              ))}
            </select>
          </div>

          {/* 自定义尺寸输入 */}
          <div className={styles.form_group}>
            <label className={styles.form_label}>自定义尺寸</label>
            <div className={styles.dimension_inputs}>
              <div className={styles.input_group}>
                <input
                  type="number"
                  value={customWidth}
                  onChange={handleWidthChange}
                  disabled={isWidthLocked}
                  min="1"
                  className={styles.dimension_input}
                />
                <span className={styles.unit}>px</span>
                {isWidthLocked && (
                  <button className={styles.lock_btn} onClick={toggleWidthLock} title="解锁宽度">
                    <i className={styles.lock_icon}>🔒</i>
                  </button>
                )}
              </div>
              <span className={styles.dimension_separator}>×</span>
              <div className={styles.input_group}>
                <input
                  type="number"
                  value={customHeight}
                  onChange={handleHeightChange}
                  min="1"
                  className={styles.dimension_input}
                />
                <span className={styles.unit}>px</span>
              </div>
            </div>
          </div>

          {/* 创建画布按钮 */}
          <button 
            className={styles.create_btn}
            onClick={() => navigate('/CanvasPage')}
            disabled={customWidth <= 0 || customHeight <= 0}
          >
            创建画布
          </button>
        </div>
      </div>
    </div>
  );
};

export default CanvasSizeSelector;